package com.article.service.Impl;


import com.article.entity.dto.UserDto;
import com.article.entity.pojo.User;
import com.article.mapper.UserMapper;
import com.article.service.UserService;
import com.article.utils.Md5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param user 用户实体类
     * @return 1:登录成功 0:登录失败
     */
    @Override
    public User login(User user) {
        // MD5加密
        User user1 = userMapper.login(user);
        if (user1 != null) {
            if (Md5Util.checkPassword(user.getPassword(), user1.getPassword())) {
                return user1;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 用户注册
     *
     * @param userDto 用户注册实体类
     * @return 1:注册成功 0:注册失败
     */
    @Override
    public int register(UserDto userDto) {
        // 判断用户名是否唯一
        if (userMapper.selectOne(new QueryWrapper<User>().eq("username", userDto.getUsername())) != null) {
            return 0;
        }
        // 判断两次密码是否一致
        if (!userDto.getPassword().equals(userDto.getPassword1())) {
            return 0;
        }
        User user = new User();
        // 进行对象拷贝
        BeanUtils.copyProperties(userDto, user);
        // 将用户密码进行md5加密
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        // 注册用户
        return userMapper.insert(user);
    }

    @Override
    public User getUserInfo(Integer id) {
        return userMapper.selectById(id);
    }
}
